<template>
  <div class="dict-management">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <h2>数据字典管理</h2>
          <el-button type="primary" @click="showAddTypeModal">
            <el-icon><Plus /></el-icon>
            新建字典类型
          </el-button>
        </div>
      </template>
      
      <div class="filters">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索字典类型名称"
          @input="filterDictTypes"
          clearable
          style="max-width: 400px"
        >
          <template #prefix><el-icon><Search /></el-icon></template>
        </el-input>
      </div>
      
      <el-table 
        :data="filteredDictTypes" 
        stripe
        border
        style="width: 100%"
      >
        <el-table-column prop="dictId" label="ID" width="130" />
        <el-table-column label="字典名称" width="200">
          <template #default="{ row }">
            <el-button type="primary" link @click="manageDictData(row)">
              {{ row.dictName }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="dictType" label="字典类型" width="200">
          <template #default="{ row }">
            <el-tag type="info">{{ row.dictType }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === '0' ? 'success' : 'danger'">
              {{ row.status === '0' ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" show-overflow-tooltip />
        <el-table-column label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-space :size="4">
              <el-button type="warning" link size="small" @click="editDictType(row)">
                编辑
              </el-button>
              <el-popconfirm
                title="确定要删除这个字典类型吗？"
                @confirm="deleteDictType(row)"
              >
                <template #reference>
                  <el-button type="danger" link size="small">
                    删除
                  </el-button>
                </template>
              </el-popconfirm>
            </el-space>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 字典类型编辑/创建对话框 -->
    <el-dialog
      v-model="showTypeModal"
      :title="isEditType ? '编辑字典类型' : '新建字典类型'"
      width="600px"
    >
      <el-form
        :model="typeForm"
        label-width="100px"
      >
        <el-form-item label="字典名称" required>
          <el-input v-model="typeForm.dictName" placeholder="如：文章分类" />
        </el-form-item>
        
        <el-form-item label="字典类型" required>
          <el-input v-model="typeForm.dictType" placeholder="如：article_category" :disabled="isEditType" />
        </el-form-item>
        
        <el-form-item label="状态">
          <el-radio-group v-model="typeForm.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="备注">
          <el-input 
            v-model="typeForm.remark" 
            type="textarea"
            :rows="3" 
            placeholder="字典类型说明"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showTypeModal = false">取消</el-button>
        <el-button type="primary" @click="saveDictType">保存</el-button>
      </template>
    </el-dialog>
    
    <!-- 字典数据管理对话框 -->
    <el-dialog
      v-model="showDataModal"
      :title="`${currentDictType?.dictName} - 数据管理`"
      width="900px"
    >
      <div class="dict-data-container">
        <div class="data-header">
          <el-button type="primary" size="small" @click="showAddDataModal">
            <el-icon><Plus /></el-icon>
            添加数据
          </el-button>
        </div>
        
        <el-table 
          :data="dictDataList" 
          stripe
          border
          style="width: 100%"
        >
          <el-table-column prop="dictSort" label="排序" width="80" sortable />
          <el-table-column prop="dictLabel" label="标签" width="150" />
          <el-table-column prop="dictValue" label="键值" width="150">
            <template #default="{ row }">
              <el-tag type="warning">{{ row.dictValue }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.status === '0' ? 'success' : 'danger'">
                {{ row.status === '0' ? '正常' : '停用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" show-overflow-tooltip />
          <el-table-column label="操作" width="150">
            <template #default="{ row }">
              <el-space :size="4">
                <el-button type="warning" link size="small" @click="editDictData(row)">
                  编辑
                </el-button>
                <el-popconfirm
                  title="确定要删除吗？"
                  @confirm="deleteDictData(row)"
                >
                  <template #reference>
                    <el-button type="danger" link size="small">
                      删除
                    </el-button>
                  </template>
                </el-popconfirm>
              </el-space>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
    
    <!-- 字典数据编辑/创建对话框 -->
    <el-dialog
      v-model="showDataEditModal"
      :title="isEditData ? '编辑字典数据' : '添加字典数据'"
      width="600px"
    >
      <el-form
        :model="dataForm"
        label-width="100px"
      >
        <el-form-item label="字典标签" required>
          <el-input v-model="dataForm.dictLabel" placeholder="如：AI&大模型" />
        </el-form-item>
        
        <el-form-item label="字典键值" required>
          <el-input v-model="dataForm.dictValue" placeholder="如：ai_llm" />
        </el-form-item>
        
        <el-form-item label="排序">
          <el-input-number v-model="dataForm.dictSort" :min="0" />
        </el-form-item>
        
        <el-form-item label="状态">
          <el-radio-group v-model="dataForm.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="备注">
          <el-input 
            v-model="dataForm.remark" 
            type="textarea"
            :rows="3" 
            placeholder="数据说明"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showDataEditModal = false">取消</el-button>
        <el-button type="primary" @click="saveDictData">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { Plus, Search } from '@element-plus/icons-vue'
import { dictAPI } from '@/api/dict'
import { ElMessage } from 'element-plus'

export default {
  name: 'CategoryManagement',
  components: {
    Plus,
    Search
  },
  data() {
    return {
      dictTypes: [],
      filteredDictTypes: [],
      dictDataList: [],
      searchKeyword: '',
      
      // 字典类型相关
      showTypeModal: false,
      isEditType: false,
      typeForm: {
        dictName: '',
        dictType: '',
        status: '0',
        remark: ''
      },
      
      // 字典数据相关
      showDataModal: false,
      showDataEditModal: false,
      isEditData: false,
      currentDictType: null,
      dataForm: {
        dictLabel: '',
        dictValue: '',
        dictSort: 0,
        dictType: '',
        status: '0',
        remark: ''
      }
    }
  },
  mounted() {
    this.loadDictTypes()
  },
  methods: {
    // ========== 字典类型管理 ==========
    
    async loadDictTypes() {
      try {
        const response = await dictAPI.getAllDictTypes()
        if (response.data.success) {
          this.dictTypes = response.data.data
          this.filterDictTypes()
        }
      } catch (error) {
        console.error('加载字典类型失败:', error)
        ElMessage.error('加载字典类型失败')
      }
    },
    
    filterDictTypes() {
      if (!this.searchKeyword.trim()) {
        this.filteredDictTypes = this.dictTypes
        return
      }
      
      const keyword = this.searchKeyword.toLowerCase()
      this.filteredDictTypes = this.dictTypes.filter(dt => 
        dt.dictName.toLowerCase().includes(keyword) ||
        dt.dictType.toLowerCase().includes(keyword)
      )
    },
    
    showAddTypeModal() {
      this.isEditType = false
      this.typeForm = {
        dictName: '',
        dictType: '',
        status: '0',
        remark: ''
      }
      this.showTypeModal = true
    },
    
    editDictType(dictType) {
      this.isEditType = true
      this.typeForm = { ...dictType }
      this.showTypeModal = true
    },
    
    async saveDictType() {
      if (!this.typeForm.dictName || !this.typeForm.dictType) {
        ElMessage.warning('请填写字典名称和类型')
        return
      }
      
      try {
        if (this.isEditType) {
          await dictAPI.updateDictType(this.typeForm.dictId, this.typeForm)
          ElMessage.success('更新成功')
        } else {
          await dictAPI.createDictType(this.typeForm)
          ElMessage.success('创建成功')
        }
        this.showTypeModal = false
        this.loadDictTypes()
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败')
      }
    },
    
    async deleteDictType(dictType) {
      try {
        await dictAPI.deleteDictType(dictType.dictId)
        ElMessage.success('删除成功')
        this.loadDictTypes()
      } catch (error) {
        console.error('删除失败:', error)
        ElMessage.error('删除失败')
      }
    },
    
    // ========== 字典数据管理 ==========
    
    async manageDictData(dictType) {
      this.currentDictType = dictType
      this.showDataModal = true
      await this.loadDictData(dictType.dictType)
    },
    
    async loadDictData(dictType) {
      try {
        const response = await dictAPI.getDictDataByType(dictType)
        if (response.data.success) {
          this.dictDataList = response.data.data
        }
      } catch (error) {
        console.error('加载字典数据失败:', error)
        ElMessage.error('加载字典数据失败')
      }
    },
    
    showAddDataModal() {
      this.isEditData = false
      this.dataForm = {
        dictLabel: '',
        dictValue: '',
        dictSort: this.dictDataList.length + 1,
        dictType: this.currentDictType.dictType,
        status: '0',
        remark: ''
      }
      this.showDataEditModal = true
    },
    
    editDictData(data) {
      this.isEditData = true
      this.dataForm = { ...data }
      this.showDataEditModal = true
    },
    
    async saveDictData() {
      if (!this.dataForm.dictLabel || !this.dataForm.dictValue) {
        ElMessage.warning('请填写标签和键值')
        return
      }
      
      try {
        if (this.isEditData) {
          await dictAPI.updateDictData(this.dataForm.dictCode, this.dataForm)
          ElMessage.success('更新成功')
        } else {
          await dictAPI.createDictData(this.dataForm)
          ElMessage.success('添加成功')
        }
        this.showDataEditModal = false
        await this.loadDictData(this.currentDictType.dictType)
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败')
      }
    },
    
    async deleteDictData(data) {
      try {
        await dictAPI.deleteDictData(data.dictCode)
        ElMessage.success('删除成功')
        await this.loadDictData(this.currentDictType.dictType)
      } catch (error) {
        console.error('删除失败:', error)
        ElMessage.error('删除失败')
      }
    },
    
    formatDate(date) {
      if (!date) return '-'
      return new Date(date).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
  }
}
</script>

<style scoped>
.dict-management {
  padding: 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.filters {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}

.dict-data-container {
  min-height: 400px;
}

.data-header {
  margin-bottom: 16px;
}
</style>
